﻿namespace Vin.Tool.Core.ConvertCategory;

/// <summary>
/// 类型转换工具类
/// </summary>
public class ConvertTool
{
    /// <summary>
    /// 将对象转换为指定类型，转换失败返回指定类型的默认值
    /// </summary>
    public static T? To<T>(object value)
    {
        try
        {
            return (T)Convert.ChangeType(value, typeof(T));
        }
        catch
        {
            return default;
        }
    }

    /// <summary>
    /// 将字符串转换为整型，转换失败返回0
    /// </summary>
    public static int ToInt32(string value)
    {
        return int.TryParse(value, out var result) ? result : 0;
    }

    /// <summary>
    /// 将字符串转换为长整型，转换失败返回0
    /// </summary>
    public static long ToInt64(string value)
    {
        return long.TryParse(value, out var result) ? result : 0;
    }

    /// <summary>
    /// 将字符串转换为布尔型，转换失败返回默认值，默认值false
    /// </summary>
    public static bool ToBoolean(string data, bool defValue = false)
    {
        //如果为空则返回默认值
        if (string.IsNullOrEmpty(data))
        {
            return defValue;
        }

        return bool.TryParse(data, out var temp) ? temp : defValue;
    }

    /// <summary>
    /// 将对象转换为布尔型，转换失败返回默认值，默认值false
    /// </summary>
    public static bool ToBoolean(object? data, bool defValue = false)
    {
        //如果为空则返回默认值
        if (data == null || Convert.IsDBNull(data))
        {
            return defValue;
        }

        try
        {
            return Convert.ToBoolean(data);
        }
        catch
        {
            return defValue;
        }
    }

    /// <summary>
    /// 将字符串转换为单精度浮点型，转换失败返回0
    /// </summary>
    public static float ToSingle(string value)
    {
        return float.TryParse(value, out var result) ? result : 0;
    }

    /// <summary>
    /// 将字符串转换为双精度浮点型，转换失败返回0
    /// </summary>
    public static double ToDouble(string value)
    {
        return double.TryParse(value, out var result) ? result : 0;
    }

    /// <summary>
    /// 将字符串转换为十进制数，转换失败返回0
    /// </summary>
    public static decimal ToDecimal(string value)
    {
        return decimal.TryParse(value, out var result) ? result : 0;
    }

    /// <summary>
    /// 将字符串转换为日期时间，转换失败返回DateTime.MinValue
    /// </summary>
    public static DateTime ToDateTime(string value)
    {
        return DateTime.TryParse(value, out var result) ? result : DateTime.MinValue;
    }

    /// <summary>
    /// 将字符串转换为枚举类型，转换失败返回默认值
    /// </summary>
    public static T ToEnum<T>(string value, T defaultValue = default) where T : struct
    {
        return Enum.TryParse(value, out T result) ? result : defaultValue;
    }
}